﻿using System;
using System.Collections.Generic;
using Gp.Scripts.Database;
using MoreMountains.Tools;
using UnityEngine.SceneManagement;

namespace Gp.Scripts.Core {
    public enum LoadingStatus {
        BeforeStart,
        
        
        During,
         
        
        AfterComplete,
    }
    
    
    public class SceneLoadEvent {
        public LoadingStatus LoadingStatus;
        public SceneLoadEvent(LoadingStatus loadingStatus) {
            LoadingStatus = loadingStatus;
        }
    }
    
    
    
    
    public static class SceneManageSystem {
        public const string LoadingSceneName = "LoadingScreen";
        private static string[] _nextScenes;
        private static Action AfterSceneLoading;
        public static bool SceneLoadingFlag { get; private set; } = false;

        public static void LoadScene(string sceneName) { }
        
        
        public static void LoadScenes(string[] scenes, Action afterLoad = null) {
            _nextScenes = scenes;
            SceneLoadingFlag = true;
            
            
            SceneManager.LoadScene(LoadingSceneName, LoadSceneMode.Additive);
            AfterSceneLoading = afterLoad;
        }


        public static void MakeSurePersistentScene() {
            var scene = SceneManager.GetSceneByName(LevelObjectConfigDatabase.PersistentSceneName);
            if (scene.IsValid()) return;

            SceneManager.LoadScene(LevelObjectConfigDatabase.PersistentSceneName, LoadSceneMode.Additive);
        }
        
        
        

        public static string[] PopLoadingSceneArgs() {
            var temp = _nextScenes;
            _nextScenes = null;
            return temp;
        }
        
        
        
        
        
        
        public static bool IsPersistentScene(this Scene scene) {
            return scene.name == LevelObjectConfigDatabase.PersistentSceneName;
        }


        public static List<string> OpeningScenes() {
            List<string> res = new();
            for (int i = 0; i < SceneManager.sceneCount; i++) {
                var scene = SceneManager.GetSceneAt(i);
                if (!scene.IsValid()) continue;
                if (scene.IsPersistentScene() || scene.IsLoadingScene()) continue;
                res.Add(scene.name);
            }
            
            return res;
        }
        

        public static bool IsLoadingScene(this Scene scene) {
            return scene.name == LoadingSceneName;
        }

        public static void AfterSceneLoadTrigger() {
            AfterSceneLoading?.Invoke();
            AfterSceneLoading = null;
            SceneLoadingFlag = false;
        }
    }
}